package com.bxait.toymail.ware.service.impl;

import com.bxait.com.constant.WareConstant;
import com.bxait.com.utils.PageUtils;
import com.bxait.com.utils.Query;
import com.bxait.com.utils.R;
import com.bxait.com.vo.ware.MergeVo;
import com.bxait.com.vo.ware.PurchaseDoneVo;
import com.bxait.com.vo.ware.PurchaseItemDoneVo;
import com.bxait.toymail.ware.entity.PurchaseDetailEntity;
import com.bxait.toymail.ware.feign.ProductFeignService;
import com.bxait.toymail.ware.service.PurchaseDetailService;
import com.bxait.toymail.ware.service.WareSkuService;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.bxait.toymail.ware.dao.PurchaseDao;
import com.bxait.toymail.ware.entity.PurchaseEntity;
import com.bxait.toymail.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Resource
    @Qualifier("purchaseDetailService")
    PurchaseDetailService detailService;


    @Resource
    @Qualifier("wareSkuService")
    WareSkuService wareSkuService;

    @Resource
    ProductFeignService productFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * @param mergeVo
     * @==============History===============<br/>
     * @Description // TODO  合并采购项
     * @Date 2023/3/25 2023/3/25
     * @Author < a href="2277411582@qq.com">chen</ a>
     * @return [com.bxait.com.vo.ware.MergeVo]
     */
    @Transactional
    @Override
    public void mergePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        // 1.如果采购信息的id为null,我们后台自动生成一条采购单记录
        if(purchaseId == null){
            PurchaseEntity purchaseEntity =
                                   new PurchaseEntity();
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            // 设置采购信息的状态
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }

        // 2.需要合并的采购项
        List<Long> items = mergeVo.getItems();

        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> collect = items.stream().map(i -> {
            // 收集发来的每一个采购项
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            detailEntity.setId(i);
            detailEntity.setPurchaseId(finalPurchaseId);
            // 设置采购项为已分配
            detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return detailEntity;
        }).collect(Collectors.toList());

        // 更新需要合并的采购项
        detailService.updateBatchById(collect);


        // 更新采购单的更新时间
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }

    /**
     * @param params
     * @==============History===============<br/>
     * @Description // TODO  查询未领取的采购单
     * @Date 2023/3/25 2023/3/25
     * @Author < a href="2277411582@qq.com">chen</ a>
     * @return [java.util.Map<java.lang.String,java.lang.Object>]
     */
    @Override
    public PageUtils queryPageUnrReceivePurchase(Map<String, Object> params) {

        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();

        wrapper.eq("status",WareConstant.PurchaseStatusEnum.CREATED.getCode()).or().eq("status",WareConstant.PurchaseStatusEnum.ASSIGNED.getCode());

        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);

    }

    /**
     * @param ids
     * @==============History===============<br/>
     * @Description // TODO  领取采购单
     * @Date 2023/3/25 2023/3/25 
     * @Author < a href="2277411582@qq.com">chen</ a>
     * @return [java.util.List<java.lang.Long>]
     */
    @Transactional
    @Override
    public void received(List<Long> ids) {
        // 1.确保当前采购单是新建或者已分配状态
        List<PurchaseEntity> collect = ids.stream()
                .map(id -> {
                    PurchaseEntity purchaseEntity = this.getById(id);
                    return purchaseEntity;
                })
                .filter(item -> {
                    if (item.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode()
                            || item.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()) {
                        return true;
                    }
                    return false;
                })
                .map(item -> {
                    item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
                    item.setUpdateTime(new Date());
                    return item;
                })
                .collect(Collectors.toList());

        // 2.更新采购单的状态
        this.updateBatchById(collect);


        // 3.改变采购项的状态
        for (PurchaseEntity purchaseEntity : collect) {
            // 采购项的总金额
            BigDecimal purchaseEntityAmount = new BigDecimal(0);
            Long id = purchaseEntity.getId();
            // 获取采购项
            List<PurchaseDetailEntity> entities = detailService.list(new QueryWrapper<PurchaseDetailEntity>().eq("purchase_id", id));

            List<PurchaseDetailEntity> collect1 = entities.stream().map(item -> {
                PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                purchaseDetailEntity.setId(item.getId());
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                try {
                    R info = productFeignService.info(item.getSkuId());
                    if(info.getCode() == 0){
                        Map<String, Object> data = (Map<String, Object>)info.get("data");
                        Double price = (Double) data.get("price");
                        BigDecimal priceNew = new BigDecimal(price).multiply(new BigDecimal(item.getSkuNum()));
                        purchaseDetailEntity.setSkuPrice(priceNew);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return purchaseDetailEntity;
            }).collect(Collectors.toList());
            // 批量更新采购项
            detailService.updateBatchById(collect1);
        }

    }

    /***
     * @param doneVo
     * @==============History===============<br/>
     * @Description // TODO  完成采购
     * @Date 2023/3/25 2023/3/25
     * @Author < a href="2277411582@qq.com">chen</ a>
     * @return [com.bxait.com.vo.ware.PurchaseDoneVo]
     */
    @Transactional
    @Override
    public void done(PurchaseDoneVo doneVo) {
        // 1.获取采购单的id
        Long id = doneVo.getId();

        // 2.每一个采购项的详情
        List<PurchaseItemDoneVo> items = doneVo.getItems();

        // 定义一个标识位,由它决定将来采购单的状态
        Boolean flag = true;
        // 这是将来需要更新的采购项信息
        List<PurchaseDetailEntity> updates = new ArrayList<>();
        BigDecimal purchaseEntityAmount = new BigDecimal(0);


        // 3.得到每一个采购项,开始更新采购项的信息
        for (PurchaseItemDoneVo item : items) {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            // 失败
            if(item.getStatus() == WareConstant.PurchaseDetailStatusEnum.ERROR.getCode()){
                flag = false;
                detailEntity.setStatus(item.getStatus());
            }else {
                // 采购成功
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                // 采购成功的是需要将库存信息进行更新
                PurchaseDetailEntity entity = detailService.getById(item.getItemId());
                // 更新采购项的价格
                try {
                    R info = productFeignService.info(entity.getSkuId());
                    if(info.getCode() == 0){
                        Map<String, Object> data = (Map<String, Object>)info.get("data");
                        Double price = (Double) data.get("price");
                        BigDecimal priceNew = new BigDecimal(price).multiply(new BigDecimal(entity.getSkuNum()));
                        detailEntity.setSkuPrice(priceNew);
                        purchaseEntityAmount.add(priceNew);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                // 更新库存信息
                wareSkuService.addStock(entity.getSkuId(),entity.getWareId(),entity.getSkuNum());
            }

            // 不管采购成功失败,都要更新采购项信息
            detailEntity.setId(item.getItemId());
            updates.add(detailEntity);
        }
        // 更新采购项信息
        detailService.updateBatchById(updates);

        // 更新采购单信息
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        purchaseEntity.setStatus(flag?WareConstant.PurchaseStatusEnum.FINISH.getCode() : WareConstant.PurchaseStatusEnum.ERROR.getCode());
        purchaseEntity.setAmount(purchaseEntityAmount);
        // 直接取第一个采购项的仓库位置
        Long itemId = items.get(0).getItemId();
        PurchaseDetailEntity detailEntity = detailService.getById(itemId);
        purchaseEntity.setWareId(detailEntity.getWareId());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }

}